package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/17 17:08
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.common.anno.Logs)")
    public void pt(){}

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        Object result = null;
        try {
            long startTime = System.currentTimeMillis();
            result = pjp.proceed();
            long endTime = System.currentTimeMillis();
            try {
                operateLogMapper.insert(OperateLog.builder()
                        .operateUserId(CurrentUserContextHolders.getUserId())
                        .operateTime(LocalDateTime.now())
                        .className(pjp.getTarget().getClass().getName())
                        .methodName(pjp.getSignature().getName())
                        .methodParams(JSONUtil.toJsonStr(pjp.getArgs()))
                        .returnValue(JSONUtil.toJsonStr(result))
                        .costTime(endTime - startTime)
                        .build()
                );
            } catch (Exception e) {
                log.error("操作日志记录失败", e);
            }
        } catch (Throwable e) {
            log.error("操作失败", e);
            result = Result.error("您的操作失败，请重试");
        }
        return result;
    }
}
